import {
  login,
  logout,
  refreshToken,
  getInfo,
  getPermissionTrees,
  ssologin
} from "@/api/login";
import {
  getAccessToken,
  getRefreshToken,
  setToken,
  removeToken
} from "@/utils/auth";

const user = {
  state: {
    access_token: getAccessToken(),
    refresh_token: getRefreshToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: []
  },

  mutations: {
    SET_ACCESS_TOKEN: (state, token) => {
      state.access_token = token;
      localStorage.setItem("access_token", token);
    },

    SET_REFRESH_TOKEN: (state, token) => {
      state.refresh_token = token;
      localStorage.setItem("refresh_token", token);
    },

    SET_NAME: (state, name) => {
      localStorage.setItem("name", name);
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      localStorage.setItem("roles", JSON.stringify(roles));
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
      localStorage.setItem("permissions", JSON.stringify(permissions));
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            commit("SET_ACCESS_TOKEN", res.data.access_token.token);
            commit("SET_REFRESH_TOKEN", res.data.refresh_token.token);
            getPermissionTrees().then(res => {
              const { allMenus, menus, btns, roles } = res.data;
              commit(
                "SET_PERMISSIONS",
                btns.map(n => n.code)
              );
              commit("SET_ROLES", roles);
              if (menus && Array.isArray(menus) && menus.length > 0)
                localStorage.setItem("routes", JSON.stringify(menus));

              // if (allMenus && Array.isArray(allMenus) && allMenus.length > 0)
              //   localStorage.setItem("allMenus", JSON.stringify(allMenus));

              return resolve();
            });
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登录
    ssologin({ commit }, code) {
      return new Promise((resolve, reject) => {
        ssologin(code)
          .then(res => {
            commit("SET_ACCESS_TOKEN", res.data.access_token.token);
            commit("SET_REFRESH_TOKEN", res.data.refresh_token.token);
            return getPermissionTrees().then(res => {
              const { allMenus, menus, btns } = res.data;
              commit(
                "SET_PERMISSIONS",
                btns.map(n => n.code)
              );
              if (menus && Array.isArray(menus) && menus.length > 0)
                localStorage.setItem("routes", JSON.stringify(menus));
              return resolve(res);
            });
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //刷新token
    RefreshToken({ commit }) {
      return new Promise((resolve, reject) => {
        const token = getRefreshToken();
        if (token) {
          refreshToken(token)
            .then(res => {
              commit("SET_ACCESS_TOKEN", res.data.access_token.token);
              commit("SET_REFRESH_TOKEN", res.data.refresh_token.token);
              resolve();
            })
            .catch(error => {
              reject(error);
            });
        } else {
          reject("refresh_token无效");
        }
      });
    },

    // 获取用户信息
    async GetInfo({ commit, state }) {
      const response = await getInfo();
      if (response)
        return new Promise(resolve => {
          const user = response.data;
          if (user) {
            // const avatar = !user.avatar
            //   ? require("@/assets/images/profile.jpg")
            //   : process.env.VUE_APP_BASE_API + user.avatar;

            commit("SET_NAME", user.displayName || user.userName);
            commit("SET_AVATAR", user.avatar);
            resolve(response);
          }
        });
    },

    // 退出系统
    LogOut({ commit }, redirect_url) {
      return new Promise((resolve, reject) => {
        return logout(redirect_url)
          .then(res => {
            commit("SET_ACCESS_TOKEN", "");
            commit("SET_REFRESH_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken("access_token");
            removeToken("refresh_token");
            localStorage.removeItem("name");
            window.location = res.data;
            // commit("SET_TOKEN", "");
            // commit("SET_ROLES", []);
            // commit("SET_PERMISSIONS", []);
            // removeToken();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    }
  }
};

export default user;
